#ifndef H_miniopt_H
#define H_miniopt_H

#include "minicon.h"

namespace Opt
{
   unsigned wtou( const WCHAR *pw, unsigned base=10, unsigned *plen=0 );
   int wtoi( const WCHAR *pw );

   enum EConstants
   {
      MaxArgs = 128,

      Err_Unknown_Lopt   = -11,
      Err_Unknown_Sopt   = -12,
      Err_Missed_Value   = -13,
      Err_Wrong_Value    = -14,
      Err_Missed_Param   = -15,
      Err_TooMany_Params = -16,

      zEConstans
   };

   int opt_err( int errcode, const WCHAR *opt=0, const WCHAR *val=0 );

   bool getargs(int& argc, WCHAR** argv);
   bool getprog(WCHAR *exec, char *name, int maxlen, bool lower=false);

   struct option
   {
      char s_opt;
      const char *l_opt;
      int *i_o;
      int (*f_o)(const WCHAR *);
   };

   int getopts( int argc, WCHAR**argv, option *options, int no, int start=1 );

   static inline bool is_slash(WCHAR c)
   { return c == L'\\' || c == L'/'; }

   static inline bool end_with_slash(const WCHAR *pw)
   { return pw && pw[0] && is_slash(pw[::lstrlen(pw)-1]); }

   static WCHAR inline last_slash_or_colon(const WCHAR *pw)
   {
      WCHAR c = L'0';
      if (pw && *pw) {
         c = pw[::lstrlen(pw)-1];
         if (is_slash(c)) c = L'\\'; else if (c != L':') c = L'\0';
      }
      return c;
   }
   
   BOOL norm_slash(const WCHAR *s, WCHAR *d, int dsz, int e_slash=0);
   int root_length(const WCHAR *nm);

   static inline BOOL is_root(const WCHAR *nm)
   {
      if (!nm || !*nm) return false;
      int rootl = root_length(nm);
      return !nm[rootl] || (!nm[rootl+1] && is_slash(nm[rootl]));
   }

   static inline bool have_wildcard( const WCHAR *fn )
   {
      while ( *fn ) {
         if (*fn == L'*' || *fn == L'?') return true;
         ++fn;
      }
      return false;
   }

   static inline bool is_dot( const WCHAR *pw )
   {
      return *pw == L'.' && (!pw[1] || (pw[1] == L'.' && !pw[2]));
   }

   static inline bool is_ntname( const WCHAR *nm )
   {
      return nm[0] == L'\\'
         && (nm[1] == L'\\' || nm[1] == L'?')
         && (nm[2] == L'.'  || nm[2] == L'?')
         &&  nm[3] == L'\\'
      ;
   }

   static inline WCHAR* nt_name(const WCHAR *src, WCHAR nt[MAX_PATH+4])
   {
      if (!::GetFullPathNameW(src, MAX_PATH, nt+4, NULL))
         return NULL;
      if (is_ntname(nt+4))
         return nt + 4;
      nt[0] = nt[1] = nt[3] = L'\\'; nt[2] = L'?';
      return nt;
   }
}

#endif /* H_miniopt_H */
